package javase.ch06.reflect;

import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;


class Teacher {
    private String name;
    private int workAge;
    private String major;

    public Teacher(String name, int workAge, String major) {
        this.name = name;
        this.workAge = workAge;
        this.major = major;
    }
}

// 学生类
class Student {
    private String name;
    private int num;
    private int age;

    public Student(String name, int num, int age) {
        this.name = name;
        this.num = num;
        this.age = age;
    }
}

public class ReflectDemo {
    public static void main(String[] args) {
        // 创建对象实例
        Teacher teacher = new Teacher("王朝", 10, "舞蹈");
        Student student = new Student("张三", 101, 18);

        // 将对象信息写入文件
        writeObjectToFile(teacher);
        writeObjectToFile(student);
    }


    public static void writeObjectToFile(Object obj) {
        try (FileWriter fw = new FileWriter("obj.txt", true)) { // 追加模式写入
            Class<?> clazz = obj.getClass();
            // 写入类名分隔线
            fw.write("----------" + clazz.getSimpleName() + "+-----------\n");

            // 获取所有属性（包括私有）
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                // 暴力破解私有属性访问权限
                field.setAccessible(true);
                try {
                    // 获取属性名和属性值并写入文件
                    String fieldName = field.getName();
                    Object fieldValue = field.get(obj);
                    fw.write(fieldName + " - " + fieldValue + "\n");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}